<template>
  <div class="content-area" >
    <el-container class="container-style">
      <el-container>
        <div style="width: 96%; margin: 0 auto; display: flex; flex-direction: column; align-items: center;">
          <div style="display: flex; align-items: center;">
            <div>
              <h2>通知管理</h2>
            </div>

            <el-select
                v-model="value"
                placeholder="选择某一小区"
                size="large"
                style="width: 240px; margin-left: 10px;"
                @change="handleSelectChange"
            >
              <el-option
                  v-for="item in communityList"
                  :key="item.id"
                  :label="item.communityName"
                  :value="item.id"
              />
            </el-select>

            <el-button
                type="primary"
                size="large"
                style="margin-left: 10px;"
                @click="clearSelection"
            >
              清空选择
            </el-button>
          </div>

          <div style="background-color: white; padding: 20px; margin-top: 10px; width: 100%">
          <div class="table-header-container">
            <div class="search-container">
              <el-select v-model="searchOption" placeholder="请选择查询方式" class="search-select">
                <el-option label="按通知标题查询" value="title"></el-option>
                <el-option label="按物业id查询" value="propertyStaffId"></el-option>
                <el-option label="按通知id查询" value="id"></el-option>
              </el-select>

              <el-input v-model="searchQuery" placeholder="请输入查询关键词" class="search-input"></el-input>
              <el-button type="primary" @click="searchNotice" class="search-button">查询</el-button>
          </div>

            <el-button type="primary" @click="handleCommunity">增加记录</el-button>
          </div>
          <table v-if="noticeForm && noticeForm.data && noticeForm.data.records.length > 0"
                 style="text-align: center; width: 100%; border-collapse: collapse;">
            <thead>
            <tr>
              <th style="width: 70px; height: 50px; border: 1px solid #eee;">通知id</th>
              <th style="width: 150px; height: 50px; border: 1px solid #eee;">通知标题</th>
              <th style="width: 100px; height: 50px; border: 1px solid #eee;">相关附件</th>
              <th style="width: 100px; height: 50px; border: 1px solid #eee;">发布通知的物业id</th>
              <th style="width: 200px; height: 50px; border: 1px solid #eee;">发布时间</th>
              <th style="width: 200px; height: 50px; border: 1px solid #eee;">更新时间</th>
              <th style="width: 50px; height: 50px; border: 1px solid #eee;">操作</th>
            </tr>
            </thead>
            <tbody>
            <tr v-for="(item, index) in noticeForm.data.records" :key="index" style="border: 1px solid #eee;">
              <td style="width: 70px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.id" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 150px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.title" :disabled="!item.isEdit" :class="{
          'normal-input-color':!item.isEdit,
          'edit-input-color': item.isEdit
        }" class="disabled-style"></el-input>
              </td>
              <td style="width: 100px; height: 40px; border: 1px solid #eee;">
                <el-button v-if="item.attachment" type="text" @click="downloadFile(item.attachment)">下载附件</el-button>
                <span v-else>无</span>
              </td>

              <td style="width: 100px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.propertyStaffId" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 200px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.publishDate" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 200px; height: 40px; border: 1px solid #eee;">
                <el-input v-model="item.updateDate" disabled class="disabled-style"></el-input>
              </td>
              <td style="width: 50px; height: 40px; border: 1px solid #eee;">
                <div class="button-group">
                  <template v-if="!item.isEdit">
                    <el-button type="default" @click="handleViewDetail(item.id)">查看通知内容</el-button>
                    <el-button type="success" @click="saveItem(item)">修改记录</el-button>
                    <el-button type="danger" @click="openDeleteDialog(item.id)">删除记录</el-button>
                  </template>
                  <template v-if="item.isEdit&&noticeForm && noticeForm.data && noticeForm.data.records.some(item => item.isEdit)">
                    <el-button type="success" @click="handleSaveEdit">保存修改</el-button>
                    <el-button type="default"  @click="handleCancelEdit" style="margin-left: 10px">取消修改</el-button>
                  </template>
                </div>
              </td>
            </tr>
            </tbody>
          </table>
          <div v-else-if="errorMessage">{{ errorMessage }}</div>
          <div v-else>暂无通知记录</div>
        </div>
          <div style="display: flex; justify-content: center; width: 100%;">
            <el-pagination
                class="footer"
                v-if="noticeForm && noticeForm.data"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currentPage"
                :page-sizes="[4, 6, 8]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="noticeForm.data.total"
            >
            </el-pagination>
          </div>
        </div>
      </el-container>
    </el-container>

    <el-dialog v-model="addDialogFormVisible" title="增加通知" width="500">
      <el-form :model="addForm">
        <el-form-item label="标题" :label-width="formLabelWidth">
          <el-input v-model="addForm.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="内容" :label-width="formLabelWidth">
          <el-input v-model="addForm.content" placeholder="请输入通知内容" />
        </el-form-item>
        <el-form-item label="附件" :label-width="formLabelWidth">
          <input type="file" ref="fileInput" @change="handleFileChange" />
        </el-form-item>
        <el-form-item label="备注" :label-width="formLabelWidth">
          <el-input v-model="addForm.remark" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="负责的物业id" :label-width="formLabelWidth">
          <el-input v-model="addForm.propertyStaffId" placeholder="请输入发布通知的物业id" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogFormVisible = false">Cancel</el-button>
          <el-button type="primary" @click="handleConfirm">
            Confirm
          </el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="dialogVisible" title="通知内容详情">
      <template #default>
        <div class="detail-content">
          <p><strong>通知内容:</strong></p>
          <pre style="white-space: pre-wrap; word-wrap: break-word;">{{ this.noticeForm.content }}</pre>
          <p v-if="this.noticeForm.remark">
            <strong>通知备注:</strong> {{ this.noticeForm.remark }}
          </p>
        </div>
      </template>
      <template #footer>
        <el-button @click="handleViewClose">关闭</el-button>
      </template>
    </el-dialog>

    <el-dialog v-model="deleteDialogFormVisible" title="删除通知" width="500">
      确定删除该通知信息？
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="deleteDialogFormVisible = false">Cancel</el-button>
          <el-button type="primary" @click="handleDelete">
            Confirm
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>
<script>
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { useRouter } from 'vue-router';
import * as echarts from 'echarts';
import { ElSwitch } from 'element-plus';

export default {
  data() {
    return {
      userName: localStorage.getItem('adminName') || '',
      noticeForm: {
        id: "",
        title: "",
        content: "",
        attachment: "",
        remark: "",
        propertyStaffId: "",
        publishDate: "",
        updateDate: ""
      },
      userStatisticsPage: null,
      errorMessage: '',
      currentPage: 1,
      pageSize: 8,
      addDialogFormVisible: false,
      addForm: {
        title: "",
        content: "",
        attachment: "",
        remark: "",
        propertyStaffId: "",
        publishDate: "",
        updateDate: ""
      },
      isEdit: false,
      editNotice: null,
      originalInfo: null,
      searchQuery: '',
      deleteId: null,
      deleteDialogFormVisible: false,
      formLabelWidth: '120px',
      searchOption: '',
      showDialog: false,
      dialogVisible: false,
      communityId: "",
      value: null,
      communityList: null
    };
  },
  setup() {
    const router = useRouter();
    return {
      router
    };
  },
  methods: {
    clearSelection() {
      // 清空选择
      this.value = null;
      this.communityId = "";
      // 重新加载默认数据
      this.fetchData();
    },
    handleViewClose(){
      this.dialogVisible = false;
      this.fetchData();
    },
    handleSelectChange(value) {
      this.communityId = value;
      this.fetchData();
    },
    async fetchCommunityList() {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          ElMessage.error('未获取到token，请重新登录');
          return;
        }
        const response = await axios.get('/api/community/search', {
          headers: {
            Authorization: token
          }
        });
        console.log(response)
        this.communityList = response.data.data;
        console.log('this.community',this.communityList)
      } catch (error) {
        ElMessage.error('获取小区列表时出错：' + error.message);
      }
    },
    handleCommunity(){
      if(this.communityId) {
        this.addDialogFormVisible = true;
      }else{
        ElMessage.info('请先选择小区')
      }
    },
    pageChange(url) {
      this.$router.push(url);
    },
    async fetchData() {
      try {
        const token = localStorage.getItem('token');
        let url = '/api/notice/page';
        let params = {
          current: this.currentPage,
          size: this.pageSize,
          communityId: this.communityId
        };
        if (this.searchOption === 'title') {
          params.title = this.searchQuery;
        }
        const response = await axios.get(url, {
          headers: {
            Authorization: token
          },
          params: params
        });
        this.noticeForm = response.data;
        this.originalInfo = {...this.noticeForm};
        if (this.noticeForm && this.noticeForm.data && this.noticeForm.data.records) {
          this.noticeForm.data.records.forEach(item => {
            item.isEdit = false;
          });
        }
      } catch (error) {
        ElMessage.error('获取通知记录失败:', error);
        this.errorMessage = '获取数据失败，请稍后重试';
      }
    },
    handleFileChange(event) {
      this.addForm.attachment = event.target.files[0];
    },
    handleSizeChange(newSize) {
      this.pageSize = newSize;
      this.currentPage = 1;
      this.fetchData();
    },
    handleCurrentChange(newPage) {
      this.currentPage = newPage;
      this.fetchData();
    },
   async handleViewDetail(id) {
      const token = localStorage.getItem('token');
      const response = await axios.get(`/api/notice/all/${id}`, {
        headers: {
          Authorization: token
        }
      });
      console.log("notice",response)
      if(response.data.code === 200){
        this.noticeForm = response.data.data[0];
      }
      this.dialogVisible = true;
    },
    handleConfirm() {
      this.confirmAdd();
    },
    async downloadFile(path) {
      try {
        const token = localStorage.getItem('token');
        const response = await axios.get('/api/file', {
          params: {
            path: path
          },
          headers: {
            Authorization: token
          },
          responseType: 'blob'
        });
        const blob = new Blob([response.data], { type: response.headers['content-type'] });
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        const contentDisposition = response.headers['content-disposition'];
        const fileName = contentDisposition ? contentDisposition.split('filename*=UTF-8\'\'')[1] : 'downloaded_file';
        a.download = fileName;
        a.click();
        window.URL.revokeObjectURL(url);
        ElMessage.success('文件下载成功');
      } catch (error) {
        ElMessage.error('文件下载失败：' + error.message);
      }
    },
    async confirmAdd() {
      try {
        const token = localStorage.getItem('token');
        const formData = new FormData();
        formData.append('propertyStaffId', this.addForm.propertyStaffId);
        formData.append('title', this.addForm.title);
        formData.append('content', this.addForm.content);
        formData.append('remark', this.addForm.remark);
        if (this.addForm.attachment) {
          formData.append('attachment', this.addForm.attachment);
        }

        const response = await axios.post(`/api/notice/publish/${this.addForm.propertyStaffId}`, formData, {
          headers: {
            Authorization: token,
            'Content-Type': 'multipart/form-data'
          }
        });

        console.log(response.data);
        if (response.data.code === 200) {
          ElMessage.success('增加通知记录成功');
          this.addDialogFormVisible = false;
        } else {
          ElMessage.error('增加通知记录失败,请输入正确信息');
        }
        this.fetchData();
      } catch (error) {
        ElMessage.error('增加通知记录时出错：' + error.message);
      }
    },
    saveItem(item) {
      item.isEdit = true;
      this.editNotice = item; // 将当前编辑的记录赋值给 this.editNotice
      this.saveEditId = item.id;
    },
    async handleSaveEdit() {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          throw new Error('token不存在');
        }
        if (!this.editNotice) {
          ElMessage.error('未找到当前编辑的通知记录');
          return;
        }
        const response = await axios.put(
            `/api/notice/update/${this.editNotice.id}`,null,
            {
              headers: {
                Authorization: token
              },
              params:{
                noticeId: this.editNotice.id,
                title: this.editNotice.title,
                content: this.editNotice.content,
                remark: this.editNotice.remark,
                attachment: this.editNotice.attachment
              }
            }
        );
        console.log('response:', response);
        if (response.data.code === 200) {
          this.isEdit = false;
          ElMessage.success('通知信息修改成功');
        } else {
          ElMessage.error(`通知信息修改失败: ${response.data.msg}`);
        }
        this.fetchData();
      } catch (error) {
        if (error.response) {
          ElMessage.error(`通知信息修改时出错: ${error.response.data.msg}`);
        } else if (error.request) {
          ElMessage.error('通知信息修改时出错: 没有收到服务器响应');
        } else {
          ElMessage.error(`通知信息修改时出错: ${error.message}`);
        }
      }
    },
    handleCancelEdit() {
      this.noticeForm = {...this.originalInfo };
      if (this.noticeForm && this.noticeForm.data && this.noticeForm.data.records) {
        this.noticeForm.data.records.forEach(item => {
          item.isEdit = false;
        });
      }
      this.isEdit = false;
    },
    async searchNotice() {
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          ElMessage.error('未授权，请先登录');
          return;
        }
        if (this.searchOption === 'title') {
          const response = await axios.get('/api/notice/page', {
            headers: {
              Authorization: token
            },
            params: {
              current: this.currentPage,
              size: this.pageSize,
              communityId: this.communityId,
              title: this.searchQuery
            }
          });
          if (response.data.code === 200) {
            this.noticeForm = response.data;
            this.originalInfo = {...this.noticeForm };
          } else {
            ElMessage.error('查询通知信息失败，请输入正确信息');
          }
        } else if (this.searchOption === 'propertyStaffId') {
          const response = await axios.get('/api/notice/list', {
            headers: {
              Authorization: token
            },
            params: {
              propertyStaffId: this.searchQuery
            }
          });
          if (response.data.code === 200) {
            this.noticeForm.data.records = response.data.data;
            this.originalInfo = {...this.noticeForm };
          } else {
            ElMessage.error('查询通知信息失败，请输入正确信息');
          }
        }else if (this.searchOption === 'id') {
          const response = await axios.get(`/api/notice/all/${this.searchQuery}`, {
            headers: {
              Authorization: token
            }
          });
          if (response.data.code === 200) {
            this.noticeForm.data.records = response.data.data;
            this.originalInfo = {...this.noticeForm };
          } else {
            ElMessage.error('查询通知信息失败，请输入正确信息');
          }
        }

      } catch (error) {
        ElMessage.error('网络错误，请稍后重试');
      }
    },
    openDeleteDialog(id){
      this.deleteId=id;
      this.deleteDialogFormVisible=true;
    },
    async handleDelete(){
      try {
        const token = localStorage.getItem('token');
        if (!token) {
          ElMessage.error('未授权，请先登录');
          return;
        }
        const response = await axios.delete(`/api/notice/delete/${this.deleteId}`, {
          headers: {
            Authorization: token
          }
        });
        if (response.data.code === 200) {
          ElMessage.success("删除成功");
          this.deleteDialogFormVisible=false;
        } else {
          ElMessage.error('删除通知信息失败');
        }
        this.fetchData();
      } catch (error) {
        ElMessage.error('网络错误，请稍后重试');
      }
    },
  },
  mounted() {
    this.fetchData();
    this.fetchCommunityList();
  }
};
</script>

<style scoped>

.footer {
  margin-top: 20px;
  text-align: center;
  padding: 10px;
  transition: margin-left 0.3s;
}

table {
  width: 100%;
  border-collapse: collapse;
}
th, td {
  border: 1px solid #eee;
  padding: 8px;
}

.container-style {
  height: 100%;
}

.header-style {
  background-color: rgb(204, 225, 234);
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 20px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.footer-style {
  text-align: center;
  background-color: rgba(129, 175, 184, 0.83);
}

.content-area {
  background-color: #f2f5fa;
  padding: 20px;
  height: calc(100vh - 120px); /* 50(header) + 10(footer padding top) + 60(footer height & bottom margin) */
  overflow-y: auto; /* 启用滚动条 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2); /* 添加阴影效果 */
}

.community-select-wrapper {
  display: flex;
  align-items: center;
}

.menu-header {
  padding: 0;
}

.button-group {
  display: flex;
  gap: 10px;
  justify-content: center;
  align-items: center;
}

.search-container {
  display: flex;
  align-items: center;
  gap: 5px;
}

.search-input {
  flex: 1;
  width: 300px;
  margin-right: 10px;
}

.search-select {
  flex: 1;
  width: 30px;
}

.search-button {
  min-width: 80px;
}

.table-header-container {
  display: flex;
  justify-content: space-between;
  width: 100%;
  margin-bottom: 10px;
}

.disabled-style {
  cursor: default;
}

.form-label-width {
  width: 120px;
}

.normal-input-color {
  color: inherit;
}

.edit-input-color {
  color: #ccc;
}

.detail-content {
  padding: 15px;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  background-color: #f9fafc;
}
</style>